Page({
  data: {
    cartItems: [], // 购物车商品列表
    statusBarHeight: 0, // 状态栏高度
    totalPrice: 0, // 总价
    selectAllStatus: false, // 全选状态,
    page: 1, // 当前页码
    pageSize: 100 // 每页显示的菜品数量
  },

  onLoad: function() {
    const windowInfo = wx.getWindowInfo();
    this.setData({
      statusBarHeight: windowInfo.statusBarHeight
    });
    this.fetchCartList();
  },
  
  onShow:function () {
    this.fetchCartList();
  },

  // 获取购物车列表
  fetchCartList: function() {
    const app = getApp();
    const userId = app.globalData.userInfo.id;
    const token = app.globalData.userInfo.token;
    
    wx.request({
      url: 'http://localhost:8080/manage/cart/list',
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      data : { 
        userId: userId,
        page: this.data.page,
        pageSize: this.data.pageSize 
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === 200) {
          const { rows } = res.data;
          const formattedCart = rows.map(item => ({
            id: item.id,
            name: item.name,
            image: item.image,
            price: item.amount,
            quantity: item.number,
            selected: false // 初始化未选中
          }));
          this.setData({ 
            cartItems: formattedCart,
            selectAllStatus: false
          });
          this.calculateTotal();
        }
      }
    });
  },

  // 单个商品选择切换
  toggleSelect: function(e) {
    const index = e.currentTarget.dataset.index;
    const items = this.data.cartItems;
    items[index].selected = !items[index].selected;
    // 更新全选状态
    const selectAllStatus = items.every(item => item.selected);
    this.setData({
      cartItems: items,
      selectAllStatus
    });
    this.calculateTotal();
  },

  // 全选切换
  toggleSelectAll: function() {
    const selectAll = !this.data.selectAllStatus;
    const items = this.data.cartItems.map(item => ({
      ...item,selected: selectAll
    }));
    
    this.setData({
      cartItems: items,
      selectAllStatus: selectAll
    });
    this.calculateTotal();
  },

  // 计算总价
  calculateTotal: function() {
    const total = this.data.cartItems
      .filter(item => item.selected)
      .reduce((sum, item) => sum + (item.price * item.quantity), 0);
    this.setData({ totalPrice: total });
  },

  // 创建订单
  createOrder: function() {
    const selectedItems = this.data.cartItems.filter(item => item.selected);
    if (selectedItems.length === 0) {
      wx.showToast({ title: '请选择商品', icon: 'none' });
      return;
    }
    wx.setStorageSync('selectedItems', selectedItems);
    wx.navigateTo({
      url: '/pages/orderdetail/orderdetail'
    });
  },

  // 减数量
  decreaseQuantity: function(e) {
    const index = e.currentTarget.dataset.index;
    const items = [...this.data.cartItems]; // 创建新数组避免引用问题
    const currentQuantity = items[index].quantity;

    if (currentQuantity > 1) {
      this.updateCartQuantity(items[index].id, currentQuantity - 1, () => {
        items[index].quantity--;
        this.setData({ cartItems: items });
        this.calculateTotal();
      });
    } else {
      this.deleteCartItem(items[index].id, () => {
        items.splice(index, 1);
        this.setData({ cartItems: items });
        this.calculateTotal();
      });
    }
  },

  // 增数量
  increaseQuantity: function(e) {
    const index = e.currentTarget.dataset.index;
    const items = [...this.data.cartItems];
    const newQuantity = items[index].quantity + 1;

    this.updateCartQuantity(items[index].id, newQuantity, () => {
      items[index].quantity = newQuantity;
      this.setData({ cartItems: items });
      this.calculateTotal();
    });
  },

  // 修改后的updateCartQuantity
  updateCartQuantity: function(cartItemId, newQuantity, callback) {
    const app = getApp();
    const token = app.globalData.userInfo.token;
    wx.request({
      url: 'http://localhost:8080/manage/cart',
      method: 'PUT',
      header: { 'Authorization': `Bearer ${token}` },
      data: { id: cartItemId, number: newQuantity },
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === 200) {
          callback?.();
        } else {
          wx.showToast({ title: '更新失败', icon: 'none' });
        }
      },
      fail: () => wx.showToast({ title: '网络错误', icon: 'none' })
    });
  },
  // 新增删除方法
  deleteCartItem: function(cartItemId, callback) {
    const app = getApp();
    const token = app.globalData.userInfo.token;
    wx.request({
      url: `http://localhost:8080/manage/cart/${cartItemId}`,
      method: 'DELETE',
      header: { 'Authorization': `Bearer ${token}` },
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === 200) {
          callback?.();
        } else {
          wx.showToast({ title: '删除失败', icon: 'none' });
        }
      },
      fail: () => wx.showToast({ title: '网络错误', icon: 'none' })
    });
  }
});